package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.DbUtil;
import com.csjy.migration.hnnd.DictTool;
import com.csjy.migration.hnnd.MD5Utils;
import com.csjy.migration.hnnd.ProgramArgument;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.PersonsRelationshipType;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 关联自然人表
 * BT_ITEM_ASSURE_SECURITY --> nd_related_natural_persons
 */
@BusinessDataConverter(
        insertSql = "INSERT INTO ND_RELATED_NATURAL_PERSONS(ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, ASSOCIATION_ID, ASSOCIATE_NAME, ASSOCIATE_CERTIFICATE, ASSOCIATE_ID_NUMBER, ASSOCIATION_TYPE_PERSON, ASSOCIATION_TYPE_LEGAL, EMPLOYER, POSITION, ADDRESS, PHONENUMBER) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        updateSql = "UPDATE ND_RELATED_NATURAL_PERSONS SET CREATE_NAME = ?, CREATE_BY = ?, CREATE_DATE = ?, UPDATE_NAME = ?, UPDATE_BY = ?, UPDATE_DATE = ?, SYS_ORG_CODE = ?, SYS_COMPANY_CODE = ?, BPM_STATUS = ?, ASSOCIATION_ID = ?, ASSOCIATE_NAME = ?, ASSOCIATE_CERTIFICATE = ?, ASSOCIATE_ID_NUMBER = ?, ASSOCIATION_TYPE_PERSON = ?, ASSOCIATION_TYPE_LEGAL = ?, EMPLOYER = ?, POSITION = ?, ADDRESS = ?, PHONENUMBER = ? WHERE ID = ?",
        findMigratedIdListSql = "SELECT T1.ID FROM ND_RELATED_NATURAL_PERSONS T1 LEFT JOIN ND_PROJECT_INFO T2 ON T1.ASSOCIATION_ID = T2.CUSTOMER_ID WHERE T2.ID = ?",
        seq = 500
)
public class NdRelatedNaturalPersons extends AbstractBusiness {

    public NdRelatedNaturalPersons(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId) throws SQLException {
        super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId);
    }

    @Override
    public void migrate() throws Exception {


        List<Map> btItemAssureSecurityList = this.sourceData.getBtItemAssureSecurityList();

        // btItemAssureSecurityList数据条件筛选 auditWorkflowNo IS NULL OR auditFlag = 2，并且是法人的数据
        List<Map> insertRowDatas = btItemAssureSecurityList.stream()
                .filter(row -> (
                        row.get("AUDITWORKFLOWNO") == ""
                        || row.get("AUDITWORKFLOWNO") == null
                        || "2".equals(row.get("AUDITFLAG").toString())
                        )
                        && null != row.get("OWNERTYPE")
                        && row.get("BUSIREGISTCODE") != null
                        && "101".equals(row.get("OWNERTYPE").toString())
                ).collect(Collectors.toList());


        for (Map btItemAssureSecurity : insertRowDatas) {
            String id = buildId(btItemAssureSecurity);
            // 判断是否需要覆盖迁移
            int needMigratedResult = this.needMigrated(id);
            if(needMigratedResult == 0) {
                continue;
            }
            try {

                // 单条插入或更新
                if (needMigratedResult == 1) {
                    this.targetDbUtil.updateByParams(updateSql, this.buildValues(btItemAssureSecurity), true);

                    // 批量插入或更新 和 单条插入或更新 二选一
//                this.batchUpdateValues.add(this.buildValues(btItemAssureSecurity));
                } else {
                    this.targetDbUtil.updateByParams(insertSql, this.buildValues(btItemAssureSecurity));

                    // 批量插入或更新 和 单条插入或更新 二选一
//                this.batchInsertValues.add(this.buildValues(btItemAssureSecurity));
                }

            }catch(Exception e) {
              if(e.getMessage().contains("C0033625") || e.getMessage().contains("违反唯一约束条件")){
                continue;
              }
              throw e;
            }
        }

//        System.out.println(idSet.stream().map(item -> "'" + item + "'").collect(Collectors.joining(",")));
    }


    public List buildValues(Map btItemAssureSecurity){

        // todo
        List values = new ArrayList();
        //ID	主键
        values.add(buildId(btItemAssureSecurity));
        //CREATE_NAME	创建人名称
        values.add(null);
        //CREATE_BY	创建人登录名称
        values.add(null);
        //CREATE_DATE	创建日期
        values.add(null);
        //UPDATE_NAME	更新人名称
        values.add(null);
        //UPDATE_BY	更新人登录名称
        values.add(null);
        //UPDATE_DATE	更新日期
        values.add(null);
        //SYS_ORG_CODE	所属部门
        values.add(null);
        //SYS_COMPANY_CODE	所属公司
        values.add("002");
        //BPM_STATUS	流程状态
        values.add(null);


        //ASSOCIATION_ID	关联ID
        values.add(this.sourceData.getBtItemBasic().get(0).get("ENTERPRISENO"));
        //ASSOCIATE_NAME	关联人姓名
        values.add(btItemAssureSecurity.get("OWNERNAME"));
        //ASSOCIATE_CERTIFICATE	关联人证件名称
        values.add("1");
        //ASSOCIATE_ID_NUMBER	关联人证件号码
        values.add(btItemAssureSecurity.get("BUSIREGISTCODE"));
        //ASSOCIATION_TYPE_PERSON	关联类型（自然人）
        values.add(DictTool.getTargetDictCode(PersonsRelationshipType.class,btItemAssureSecurity.get("RELATIONTYPE")));
        //ASSOCIATION_TYPE_LEGAL	关联类型（法人）
        values.add(null);
        //EMPLOYER	工作单位 旧系统无此数据
        values.add(null);
        //POSITION	职位 旧系统无此数据
        values.add(null);
        //ADDRESS	通讯地址
        values.add(btItemAssureSecurity.get("OWNERADDRESS"));
        //PHONENUMBER	手机号码
        values.add(btItemAssureSecurity.get("LINKTEL"));


        return values;
    }

    public String buildId(Map btItemAssureSecurity){
        // 基础表数据业务主键
        String ndCounterGuaranteeMeasuresOriginalId = this.sourceData.getBtItemBasic().get(0).
                get("ENTERPRISENO")
            + btItemAssureSecurity.get("BUSIREGISTCODE").toString();
        return MD5Utils.stringToMD5(ndCounterGuaranteeMeasuresOriginalId);
    }
}
